<?php

namespace mpend\models;

use Yii;
use yii\base\Model;
use common\exceptions\ModelHttpException;
use mpend\models\UserCompatibleModel;

/**
 * 用户注册
 * Login form
 */
class ReLoginForm extends Model {

    public $token = null;
    private $_user = null;

    public function reLogin() {
        $token = $this->token;
        if (!$token->user_id || time() > $token->expired_at) {
            throw new ModelHttpException('登录令牌失效，请重新登录');
        }
        $user = $this->getUser();
        $token = $this->token;
        $token->expired_at = time() + 86400 * 15;
        if (!$token->save()) {
            throw new ModelHttpException('登录失败', $token->firstErrors);
        }
        $user->token = $token;
        return $user;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = UserCompatibleModel::findIdentity($this->token->user_id);
        }
        return $this->_user;
    }

}
